/**
 * 
 */
package fotobook.data;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;

/**
 * @author n7568045
 * 
 */
public class FileAccessService {

	private static final DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();
	private static final String KIND = "FILE";
	private final User user;

	public FileAccessService(final User s) {
		this.user = s;
	}

	public String createFile(final File f) {
		final Entity e = new Entity(KIND);
		e.setProperty("filename", f.getFilename());
		e.setProperty("user", this.user.getId());
		final Key k = datastore.put(e);
		final String id = KeyFactory.keyToString(k);
		return id;
	}

	public File retrieveFile(final String id) {
		final Key k = KeyFactory.stringToKey(id);
		final PreparedQuery q = datastore.prepare(new Query(KIND, k).addFilter(
				"user", FilterOperator.EQUAL, this.user.getId()));
		final Entity e = q.asSingleEntity();
		final File file = new File() {
			{
				this.filename = e.getProperty("filename").toString();
			}

			private String filename;

			@Override
			public String getFilename() {
				return this.filename;
			}
		};
		return file;
	}

	public List<File> retrieveFiles() {
		final PreparedQuery q = datastore.prepare(new Query(KIND).addFilter(
				"user", FilterOperator.EQUAL, this.user.getId()));
		final List<Entity> list = q.asList(FetchOptions.Builder.withDefaults());
		final List<File> files = new ArrayList<File>();
		for (final Entity e : list) {
			final File f = new File() {
				{
					this.filename = e.getProperty("filename").toString();
				}

				private String filename;

				@Override
				public String getFilename() {
					return this.filename;
				}

				@Override
				public String toString() {
					return filename;
				}
			};
			files.add(f);
		}
		return files;
	}

	public void updateFile() {

	}

	public void deleteFile() {

	}
}
